<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-15
 * Time: 下午5:54
 */
namespace Home\Controller;
use Think\Controller;
class CommonController extends Controller {

    protected function _initialize(){
		$this->isFromJalis();
//        echo(CONTROLLER_NAME);die;
        if(CONTROLLER_NAME!='User'){
            Cookie('__forward__',U(CONTROLLER_NAME."/".ACTION_NAME));
        }
        if((ACTION_NAME != 'add') && (ACTION_NAME != 'upload')){
            define('UID', is_login());
            if(!UID){
                $this->redirect('/Home/Desk/index');
            }
        }
        /* 读取数据库中的配置 */
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
            S('DB_CONFIG_DATA',$config);
        }
        C($config); //添加配置
        $mode = C('SCHOOL_CONFIG');
        switch($mode){
            case 1://随机，显示全部机构
                $unitList           = array();
                $departmentModel    = M('department');
                $unitList           = $departmentModel->where('city=320000')->order('convert (name using  gb2312) asc')->select();//目前只显示江苏的
                break;
            case 2://按工作日分配
                $school =M('option')->where(array('type'=>'2'))->getField('value,start_day,end_day');
                $now=strtotime(date('Y-m-d'));
                $school_id=array();//默认学校id
                foreach($school as $k=>$v){
                    $start=strtotime($v['start_day']);
                    $end=strtotime($v['end_day']);
                    if($start<=$now&&$now<=$end ){
                        $school_id[]=$v['value'];
                    }
                }
                $unitList           = array();
                $departmentModel    = M('department');
                $unitList           = $departmentModel->where('city=320000')->order('convert (name using  gb2312) asc ')->select();//目前只显示江苏的
                break;
        }
        $this->assign('jgList',$unitList);
        $this->assign('config',$config);
        $this->assign('mr_school',$school_id);//按工作日分配默认学校id传回页面
//        $this->assign('user_message', session('user_auth'));
//        var_dump($this->Menu());
        $this->assign('__MENU__',$this->getMenu());
    }
	
	//判断链接是否来自www.jalis.nju.edu.cn，有伪造风险
    public function isFromJalis()
    {
        //$referer = $_SERVER['HTTP_REFERER'];
        //if(stristr($referer,'jalis.nju.edu.cn')!==false){
            if(is_login()==0){//未登录，则模拟登录
                $uid = I('uid',0,'intval');
                $uid = idDecode($uid);
                $user = M('User')->field('*')->where(['id'=>$uid])->find();
                if(!empty($user)){
                    session('user_auth',['uid'=>$user['id'],'username'=>$user['username'],'role_id'=>$user['typeid']]);
                }
            }
        //}
    }

    /*
     * 获取菜单
     */
    public function getMenu($controller=CONTROLLER_NAME){
        if(empty($menus)){
            // 获取主菜单
            $where['pid']   =   0;
            $where['hide']  =   0;
            $where['module'] = 'Home';
            if(!C('DEVELOP_MODE')){ // 是否开发者模式
                $where['is_dev']    =   0;
            }
            $menus['main']  =   M('Menu')->where($where)->order('sort asc')->field('id,title,url')->select();
            $id=array();
            $menus['child'] =   array(); //设置子节点
            foreach($menus['main'] as $key =>$item){
                $AUTH = new \Think\Auth();
                $rule = MODULE_NAME.'/'.$item['url'];
                if(!IS_ROOT && !$AUTH->check($rule, UID)){
                    unset($menus['main'][$key]);
                    continue;
                }
                if(CONTROLLER_NAME.'/'.ACTION_NAME == $item['url']){
                    $menus['main'][$key]['class'] = 'active';
                }
                $id[]=$item['id'];
            }
            //查找二级菜单
            $map['pid']=array('IN',$id);
            $rs =M('Menu')->where($map)->field('url')->select();
            $urls=array();
            foreach($rs as $key=>$item){
                $urls []= $item['url'];
            }
            $map0 =array();
            $map0['pid'] !=0;
            $map0['module'] = 'Home';
            $map0['url'] =array('IN',$urls);
            // 查找当前子菜单
            $rs = M('Menu')->where($map0)->field('pid')->select();
            $pid=array();
            foreach($rs as $key=>$item){
                $pid[]=$item['pid'];
            }
            if($pid){
                // 查找当前主菜单
                $map1=array();
                $map1['pid']=array('IN',$pid);
                $rs =  M('Menu')->where($map1)->select();
                $nav['pid']=array();
                foreach($rs as $key=>$item ){
                    $nav['pid'][]=$item['pid'];
                }
                foreach ($menus['main'] as $key => $item) {
                    // 获取当前主菜单的子菜单项
//                    if($item['id'] == $nav['pid']){
                    $menus['main'][$key]['class']='current';
                    //生成child树
                    $groups = M('Menu')->where(array('group'=>array('neq',''),'pid' =>$item['id']))->distinct(true)->getField("group",true);
                    //获取二级分类的合法url
                    $where          =   array();
                    $where['pid']   =   $item['id'];
                    $where['hide']  =   0;
                    if(!C('DEVELOP_MODE')){ // 是否开发者模式
                        $where['is_dev']    =   0;
                    }
                    $second_urls = M('Menu')->where($where)->getField('id,url');
                    if (!IS_ROOT) {
                        $to_check_urls = array();
                        foreach ($second_urls as $key => $to_check_url) {
                            if (stripos($to_check_url, MODULE_NAME) !== 0) {
                                $rule = MODULE_NAME . '/' . $to_check_url;
                            } else {
                                $rule = $to_check_urls;
                            }
                            $AUTH = new \Think\Auth();
                            if ($AUTH->check($rule, UID)) {
                                $to_check_urls[] = $to_check_url;
                            }
                        }
                    }
                    // 按照分组生成子菜单树
                    foreach ($groups as $g) {
                        $map = array('group'=>$g);
                        if(isset($to_check_urls)){
                            if(empty($to_check_urls)){
                                // 没有任何权限
                                continue;
                            }else{
                                $map['url'] = array('in', $to_check_urls);
                            }
                        }
                        $map['pid']     =   $item['id'];
                        $map['hide']    =   0;
                        if(!C('DEVELOP_MODE')){ // 是否开发者模式
                            $map['is_dev']  =   0;
                        }
                        $menuList = M('Menu')->where($map)->field('id,pid,title,url,tip')->order('sort asc')->select();
                        $menus['child'][$g] = list_to_tree($menuList, 'id', 'pid', 'operater', $item['id']);
                    }
//                    }
                }
            }
            session('SCHOOL_MENU_LIST.'.$controller,$menus);
        }
//        var_dump($menus);
        return $menus;
    }

    /*
     * 通用分页列表数据集获取方法
     */
    protected function lists ($model,$where=array(),$order='',$field=true,$ros){
//        var_dump($ros);die;
        $options    =   array();
        $REQUEST    =   (array)I('get.');
        if(is_string($model)){
            $model  =   M($model);
        }

        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        unset($REQUEST['_order'],$REQUEST['_field']);

        if(empty($where)){
            $where  =   array('status'=>array('egt',0));
        }
        if( !empty($where)){
            $options['where']   =   $where;
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();
        if($ros){
                $listRows = $ros;
            }else{
                $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
            }
//            if( isset($REQUEST['r']) ){
//                $listRows = (int)$REQUEST['r'];
//            }else{
//                $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
//            }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if($total>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $options['limit'] = $page->firstRow.','.$page->listRows;

        $model->setProperty('options',$options);

     return $model->field($field)->select();
//       echo $model->getLastSql();die;
    }
}